package quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <h1></h1>
 *
 * @author zhh 2019-06-03
 */
public class SimpleTriggerScheduler {
    public static void main(String[] args) throws SchedulerException {
        // 打印当前的执行时间
        System.out.println("Current Exec Time is: " + LocalDateTime.now());
        // 创建一个 JobDetail 实例，将该实例与 SimpleTriggerJob.class 绑定
        JobDetail jobDetail = JobBuilder.newJob(SimpleTriggerJob.class).withIdentity("myJob").build();
        // 距离当前时间4秒钟后执行且仅执行一次任务
        Date startTime = new Date();
        // 距离当前时间4秒钟后首次执行任务，之后每隔2秒钟重复执行任务
        startTime.setTime(startTime.getTime() + 4000L);
        // 距离当前时间6秒钟后为止
        Date endTime = new Date();
        endTime.setTime(endTime.getTime() + 6000L);
        // 创建一个 Trigger 实例，定义该 job 立即执行明知道距离当前时间6秒钟后停止
        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("myTrigger", "group1")
                .startAt(startTime)
                .endAt(endTime)
                // 每隔2秒钟重复执行任务
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                                .withIntervalInSeconds(2)
                                // .withRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY)
                                .withRepeatCount(3)
                )
                .build();
        // 创建 Schedule 实例
        StdSchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
        scheduler.start();
        scheduler.scheduleJob(jobDetail, trigger);
    }
}
